const express = require('express');
const router = express.Router();
const db = require('../database/db'); // 假设存在数据库连接模块

// 获取订单列表接口
router.get('/', async (req, res) => {
  try {
    const { search, status, date } = req.query;
    let query = 'SELECT * FROM orders WHERE 1=1';
    const params = [];

    if (search) {
      query += ' AND (id LIKE ? OR customer LIKE ?)';
      params.push(`%${search}%`, `%${search}%`);
    }
    if (status) {
      query += ' AND status = ?';
      params.push(status);
    }
    if (date) {
      query += ' AND date = ?';
      params.push(date);
    }

    const orders = await db.all(query, params);
    res.json(orders);
  } catch (err) {
    console.error('获取订单失败:', err);
    res.status(500).json({ error: '获取订单失败' });
  }
});

// 订单详情接口 - 支持微信扫码查看
router.get('/detail/:id', async (req, res) => {
  try {
    const orderId = req.params.id;
    // 从数据库查询订单信息
    const order = await db.get('SELECT * FROM orders WHERE id = ?', [orderId]);
    if (!order) {
      return res.status(404).send('订单不存在');
    }
    // 返回适合微信浏览器查看的HTML页面
    res.send(`
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>订单详情</title>
        <style>
          body { font-family: sans-serif; padding: 20px; max-width: 500px; margin: 0 auto; }
          .order-item { margin: 15px 0; padding-bottom: 10px; border-bottom: 1px solid #eee; }
          .label { font-weight: bold; display: inline-block; width: 80px; }
          .status { color: #1890ff; }
        </style>
      </head>
      <body>
        <h1 style="text-align: center; color: #1890ff;">订单详情</h1>
        <div class="order-item"><span class="label">订单号:</span> ${order.id}</div>
        <div class="order-item"><span class="label">客户:</span> ${order.customer}</div>
        <div class="order-item"><span class="label">金额:</span> ¥${order.amount.toFixed(2)}</div>
        <div class="order-item"><span class="label">状态:</span> <span class="status">${order.status}</span></div>
        <div class="order-item"><span class="label">日期:</span> ${new Date(order.date).toLocaleDateString()}</div>
      </body>
      </html>
    `);
  } catch (err) {
    console.error('订单查询错误:', err);
    res.status(500).send('服务器错误');
  }
});

module.exports = router;